package artxun.commenadapterdr;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 通用的viewholder 用于和convertview绑定
 * V2.0 加入多类型支持,所以需要引入layoutid和posion成员
 */
public class ViewHolder {
    private SparseArray<View> mViews;//id--view
    private View mConvertView;
    public int mLayoutId;

    public ViewHolder(Context context, ViewGroup parent, int layoutId) {
        mViews = new SparseArray<>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        mConvertView.setTag(this);
        mLayoutId = layoutId;
    }

    public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId) {
        if (convertView == null) {
            return new ViewHolder(context, parent, layoutId);
        }
        //复用时候更新position
        ViewHolder currentViewHolder = (ViewHolder) convertView.getTag();
        //多种类型如果layoutid不同，则重新创建
        if (currentViewHolder.mLayoutId != layoutId) {
            return new ViewHolder(context, parent, layoutId);
        }
        return currentViewHolder;
    }

    public <T extends View> T getItemView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }
}
